import React, {Component} from 'react';
import './Search.css';
import SearchNav from "../../components/Search/SearchNav/SearchNav";
import HotSearch from "../../components/Search/HotSearch/HotSearch";
import SingerList from "../../components/Singers/SingerList/SingerList";
import SearchMusicList from "../../components/Search/SearchMusicList/SearchMusicList";

class Search extends Component {
	constructor(props) {
		super(props);

		this.state = {
			hotSearch: [], // 热门搜索
			singers: [], // 歌手
			song_list: [], // 歌单
			songs: [], // 歌曲
		}

	}

	// 组件挂载完毕
	componentDidMount() {
		this.getHotSearch.call(this);

	}

	// 获取关键词，请求列表
	getListByKeyword(keyword) {
		// console.log('father', keyword);
		this.$navChild.changeChild(keyword);

		this.$axios([
			{
				url: '/search/suggest',
				params: {
					keywords: keyword
				}
			},
			{
				url: '/search',
				params: {
					keywords: keyword
				}
			}
		]).then(res => {
			// console.log(res[0]);
			// console.log(res[1]);
			if (res[0].code === 200) {
				this.setState(state => {
					return {
						singers: res[0].result.artists || [],
						song_list: res[0].result.playlists || []
					}
				})
			}
			if (res[1].code === 200) {
				this.setState(state => {
					return {
						songs: res[1].result.songs || []
					}
				})
			}
		})
	}

	// 清空输入框
	cleanKeyword() {
		this.setState(state => {
			return {
				singers: [],
				song_list: [],
				songs: []
			}
		})
	}

	// 返回上一页
	pageBack() {
		this.props.history.go(-1);
	}

	// 获取子组件
	getChild(child) {
		this.$navChild = child;
		// console.log(this.$navChild);
	}

	// 获取热门音乐
	getHotSearch() {
		this.$axios({
			url: '/search/hot'
		}).then(res => {
			// console.log(res);
			if (res.code === 200) {
				this.setState(state => {
					return {
						hotSearch: res.result.hots || []
					}
				})
			}
		})
	}

	render() {
		return (
			<div className='search'>
				<SearchNav pageBack={this.pageBack.bind(this)} cleanKeyword={this.cleanKeyword.bind(this)}
					getChild={this.getChild.bind(this)} getListByKeyword={this.getListByKeyword.bind(this)}/>

				{!this.state.singers.length && !this.state.song_list.length && !this.state.songs.length ? (
					<div>
						<div className="hotTitle">热门搜索</div>
						<HotSearch hotSearch={this.state.hotSearch} getListByKeyword={this.getListByKeyword.bind(this)}/>
					</div>
				) : null}

				{this.state.singers.length ? (
					<div>
						<h1 className="listTitle">相关歌手</h1>
						<SingerList singerList={this.state.singers}/>
					</div>
				) : null}

				{this.state.song_list.length ? (
					<div>
						<h1 className="listTitle">相关歌单</h1>
						<SingerList singerList={this.state.song_list}/>
					</div>
				) : null}

				<div>
					<SearchMusicList songs={this.state.songs}/>
				</div>
			</div>
		);
	}
}

export default Search;